package st.business.tepth.business;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.TypeReference;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import io.reactivex.disposables.Disposable;
import st.business.tepth.R;
import st.business.tepth.business.event.ICEvent;
import st.business.tepth.business.event.StartBrotherEvent;
import st.business.tepth.business.login.LoginDelegate;
import st.business.tepth.business.user.UserDelegate;
import st.business.tepth.business.visitor.VisitorDelegate;
import st.business.tepth.config.Url;
import st.business.tepth.manager.UserBean;
import st.business.tepth.manager.UserManager;
import st.shadow.library.core.base.fragment.BaseMainFragment;
import st.shadow.library.core.net.callback.IError;
import st.shadow.library.core.net.callback.ISuccess;
import st.shadow.library.core.net.data.ObjConverter;
import st.shadow.library.core.net.rx.RxRestClient;
import st.shadow.library.core.util.utilcode.util.ToastUtils;


/**
 * 主界面
 *
 * @author zhangyu
 * @date 2019/1/11
 */
public class RootDelegate extends BaseMainFragment {
    private enum ICState {
        Init_Person,
        Login_Ing,
        Login_Succeed,
        Login_Failed,
        User_User,
        Login_User
    }

    private ICState mICState = ICState.Init_Person;
    private Disposable mDisposable;

    public static RootDelegate newInstance() {
        return new RootDelegate();
    }


    @Override
    public Object setLayout() {
        return R.layout.delegate_root;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        loadRootFragment(R.id.view_content, VisitorDelegate.newInstance());
        EventBus.getDefault().register(this);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }

    @Subscribe
    public void startBrotherEvent(StartBrotherEvent event) {
        start(event.mFragment);
    }

    @Subscribe
    public void ICEvent(ICEvent event) {
        String code = event.mCode;
        if (code != null) {
            Log.e("ICEvent", event.mName);
        }
        switch (mICState) {
            case Init_Person:
                if (code != null) {
                    login(code, 0);
                    mICState = ICState.Login_Ing;
                }
                break;
            case Login_Ing:
                break;
            case Login_Succeed:
                if (code == null) {
                    //登出
                    onLogout();
                    mICState = ICState.Init_Person;
                }
                break;
            case Login_Failed:
                mICState = ICState.Init_Person;
                break;
            case User_User:
                if (code != null) {
                    if (!code.equals(UserManager.getInstance().getCurrentUserCode())) {
                        login(code, 2);
                        mICState = ICState.Login_Ing;
                    }
                }
                break;
            case Login_User:
                if (code != null) {
                    login(code, 1);
                    mICState = ICState.Login_Ing;
                }
                break;
        }
    }

    /**
     * 用户界面新用户卡片登录
     */
    public void userToUser() {
        UserDelegate userDelegate = findChildFragment(UserDelegate.class);
        if (userDelegate != null) {
            userDelegate.loadData();
        }
    }

    /**
     * 登录界面卡片登录
     */
    private void loginToUser() {
        LoginDelegate loginDelegate = findChildFragment(LoginDelegate.class);
        if (loginDelegate != null) {
            loginDelegate.startWithPop(UserDelegate.newInstance());
        }
    }

    /**
     * 游客页面卡片登录
     */
    public void visitorToUser() {
        VisitorDelegate visitorDelegate = findChildFragment(VisitorDelegate.class);
        if (visitorDelegate != null) {
            visitorDelegate.startWithPop(UserDelegate.newInstance());
        }
    }

    /**
     * 退出登录到游客页面
     */
    public void onLogout() {
        UserDelegate userDelegate = findChildFragment(UserDelegate.class);
        if (userDelegate != null) {
            userDelegate.startWithPop(VisitorDelegate.newInstance());
            mICState = ICState.Init_Person;
        }
    }

    /**
     * 登录页面手动登录
     */
    public void onLogin() {
        VisitorDelegate visitorDelegate = findChildFragment(VisitorDelegate.class);
        if (visitorDelegate != null) {
            visitorDelegate.startWithPop(UserDelegate.newInstance());
            mICState = ICState.User_User;
        }
    }

    /**
     * 游客页面点击登录
     */
    public void onVisitorToLogin() {
        VisitorDelegate visitorDelegate = findChildFragment(VisitorDelegate.class);
        if (visitorDelegate != null) {
            visitorDelegate.startWithPop(LoginDelegate.newInstance());
            mICState = ICState.Login_User;
        }
    }

    private void login(String code, final int type) {
        mDisposable = RxRestClient.builder()
                .url(Url.UserLogin)
                .params("jobNo", code)
                .params("type", 0)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        UserBean userBean = convertToUser(response);
                        if (userBean != null) {
                            UserManager.getInstance().saveUser(userBean);
                            mICState = ICState.Login_Succeed;
                            switch (type) {
                                case 0:
                                    visitorToUser();
                                    break;
                                case 1:
                                    loginToUser();
                                    break;
                                case 2:
                                    userToUser();
                                    break;
                            }
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mICState = ICState.Login_Failed;
                        ToastUtils.showShort(msg);
                    }
                })
                .build()
                .get();
    }


    private UserBean convertToUser(String response) {
        return new ObjConverter<UserBean>().convert(response
                , new TypeReference<UserBean>() {
                });
    }
}
